package com.shenjinzheng.movie_ticket_app

import android.os.Bundle
import android.util.Log
import androidx.appcompat.widget.SearchView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.shenjinzheng.movie_ticket_app.databinding.ActivityMainBinding
import com.shenjinzheng.movie_ticket_app.viewmodel.MovieViewModel
import com.shenjinzheng.movie_ticket_app.viewmodel.MovieViewModelFactory
import com.shenjinzheng.movie_ticket_app.repository.MovieRepository
import com.shenjinzheng.movie_ticket_app.network.RetrofitClient
import com.shenjinzheng.movie_ticket_app.adapter.MovieAdapter

class MainActivity : AppCompatActivity() {

    private lateinit var movieViewModel: MovieViewModel
    private lateinit var binding: ActivityMainBinding
    private lateinit var movieAdapter: MovieAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 初始化 DataBinding
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 创建 MovieRepository 和 MovieViewModel 实例
        val movieRepository = MovieRepository(RetrofitClient.apiService)
        movieViewModel = ViewModelProvider(this, MovieViewModelFactory(movieRepository))
            .get(MovieViewModel::class.java)

        // 设置 RecyclerView 和 Adapter
        movieAdapter = MovieAdapter(emptyList(),this)
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = movieAdapter

        // 观察 ViewModel 中的电影数据
        val apiKey = "0e99217fabeed0920d85def5d46c44a6"
        movieViewModel.loadMovies(apiKey)

        // 观察电影数据，并更新 RecyclerView
        movieViewModel.movies.observe(this, Observer { movieList ->
            movieAdapter.updateMovies(movieList)
        })
        // 设置搜索框的查询文本监听器
        val searchView = findViewById<SearchView>(R.id.searchView)
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                if (!query.isNullOrEmpty()) {
                    movieViewModel.searchMovies(apiKey, query)  // 传递查询字符串到 ViewModel
                }
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                return false  // 你也可以实现实时搜索
            }
        })
        // 监听 RecyclerView 滑动事件以实现分页加载
        binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val totalItemCount = layoutManager.itemCount
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()

                // 如果滚动到底部并且当前不是在加载状态，就加载下一页的数据
                if (lastVisibleItemPosition == totalItemCount - 1) {
                    Log.d("MainActivity", "Loading more movies...")
                    val apiKey = "0e99217fabeed0920d85def5d46c44a6"  // 替换为实际的 API Key
                    movieViewModel.loadMovies(apiKey)  // 加载更多数据
                }
            }
        })
    }
}
